/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package br.com.menosehmais.framework.converter;

import br.com.caelum.vraptor.Convert;
import br.com.caelum.vraptor.Converter;
import br.com.caelum.vraptor.converter.ConversionError;
import br.com.caelum.vraptor.ioc.ApplicationScoped;
import br.com.menosehmais.framework.persistence.Id;
import java.util.ResourceBundle;

/**
 *
 * @author Quintino
 */
@Convert(Id.class)
@ApplicationScoped
public class IdConverter implements Converter<Id> {

    @Override
    public Id convert(String value, Class<? extends Id> type, ResourceBundle bundle) {
        return fromString(value);
    }

    public static Id fromString(String value) {
        Id id = null;

        try {
            id = new Id( value );
        } catch (Exception e) {
            throw new ConversionError( "Id: " + value + ", é inválido. " + e.getMessage() );
        }
        
        return id;
    }

    public static String asString(Id id){
        if(id == null) {
            return null;
        }
        return id.toString();
    }
}
